import router from '@system.router'
import prompt from '@system.prompt'
import storage from '@system.storage'

export default {
  data: {
    playerData: null,
    caseStatistics: [],
    interrogationStats: [],
    achievements: [],
    rankingData: [],
    chartData: {
      successRate: [],
      skillProgress: [],
      caseCompletion: [],
      monthlyStats: []
    },
    currentView: 'overview',
    timeRange: 'all',
    comparisonMode: false
  },

  onInit() {
    this.loadStatistics()
    this.generateChartData()
    this.calculateRankings()
  },

  onShow() {
    this.loadStatistics()
  },

  loadStatistics() {
    // 加载玩家统计数据
    storage.get({
      key: 'playerData',
      success: (data) => {
        if (data) {
          this.playerData = JSON.parse(data.data || data)
        }
      }
    })

    // 加载案件统计
    storage.get({
      key: 'caseStatistics',
      success: (data) => {
        if (data) {
          this.caseStatistics = JSON.parse(data.data || data)
        } else {
          this.initializeCaseStatistics()
        }
      }
    })

    // 加载审讯统计
    storage.get({
      key: 'interrogationStats',
      success: (data) => {
        if (data) {
          this.interrogationStats = JSON.parse(data.data || data)
        } else {
          this.initializeInterrogationStats()
        }
      }
    })

    // 加载成就数据
    storage.get({
      key: 'achievements',
      success: (data) => {
        if (data) {
          this.achievements = JSON.parse(data.data || data)
        } else {
          this.initializeAchievements()
        }
      }
    })
  },

  initializeCaseStatistics() {
    this.caseStatistics = {
      totalCases: 0,
      solvedCases: 0,
      failedCases: 0,
      successRate: 0,
      averageCompletionTime: 0,
      difficultyBreakdown: {
        easy: { total: 0, solved: 0 },
        medium: { total: 0, solved: 0 },
        hard: { total: 0, solved: 0 }
      },
      categoryBreakdown: {
        murder: { total: 0, solved: 0 },
        theft: { total: 0, solved: 0 },
        missing: { total: 0, solved: 0 }
      },
      monthlyStats: this.generateMonthlyStats()
    }
  },

  initializeInterrogationStats() {
    this.interrogationStats = {
      totalInterrogations: 0,
      successfulInterrogations: 0,
      averageQuestionsPerInterrogation: 0,
      contradictionDiscoveryRate: 0,
      lyingDetectionRate: 0,
      skillUsage: {
        psychology: 0,
        observation: 0,
        logic: 0
      },
      questionTypes: {
        alibi: 0,
        relationship: 0,
        secret: 0,
        evidence: 0,
        confrontation: 0
      },
      suspectBreakdown: []
    }
  },

  initializeAchievements() {
    this.achievements = [
      {
        id: 1,
        name: '新手侦探',
        description: '完成第一个案件',
        icon: '🕵️',
        unlocked: false,
        progress: 0,
        target: 1,
        category: 'cases'
      },
      {
        id: 2,
        name: '真相追寻者',
        description: '连续解决5个案件',
        icon: '🔍',
        unlocked: false,
        progress: 0,
        target: 5,
        category: 'cases'
      },
      {
        id: 3,
        name: '心理大师',
        description: '在审讯中发现50个矛盾点',
        icon: '🧠',
        unlocked: false,
        progress: 0,
        target: 50,
        category: 'interrogation'
      },
      {
        id: 4,
        name: '完美推理',
        description: '解决一个困难案件且发现所有证据',
        icon: '💎',
        unlocked: false,
        progress: 0,
        target: 1,
        category: 'skills'
      }
    ]
  },

  generateMonthlyStats() {
    const months = ['1月', '2月', '3月', '4月', '5月', '6月']
    return months.map(month => ({
      month: month,
      cases: Math.floor(Math.random() * 10) + 1,
      solved: Math.floor(Math.random() * 8) + 1,
      successRate: Math.floor(Math.random() * 40) + 60
    }))
  },

  generateChartData() {
    // 生成图表数据
    this.chartData.successRate = this.generateSuccessRateData()
    this.chartData.skillProgress = this.generateSkillProgressData()
    this.chartData.caseCompletion = this.generateCaseCompletionData()
    this.chartData.monthlyStats = this.generateMonthlyChartData()
  },

  generateSuccessRateData() {
    return [
      { name: '总体', value: this.playerData?.successRate || 0 },
      { name: '简单', value: 85 },
      { name: '中等', value: 70 },
      { name: '困难', value: 45 }
    ]
  },

  generateSkillProgressData() {
    const skills = this.playerData?.interrogationSkills || { psychology: 1, observation: 1, logic: 1 }
    return [
      { name: '心理学', value: skills.psychology, max: 10, color: '#ff6b6b' },
      { name: '观察力', value: skills.observation, max: 10, color: '#4ecdc4' },
      { name: '逻辑推理', value: skills.logic, max: 10, color: '#45b7d1' }
    ]
  },

  generateCaseCompletionData() {
    return [
      { category: '谋杀案', completed: 12, total: 15 },
      { category: '盗窃案', completed: 8, total: 10 },
      { category: '失踪案', completed: 6, total: 8 },
      { category: '诈骗案', completed: 4, total: 6 }
    ]
  },

  generateMonthlyChartData() {
    return this.caseStatistics?.monthlyStats || this.generateMonthlyStats()
  },

  calculateRankings() {
    // 计算排行榜数据
    this.rankingData = [
      {
        rank: 1,
        name: '神探柯南',
        level: 25,
        solved: 89,
        successRate: 98.5,
        avatar: '🕵️'
      },
      {
        rank: 2,
        name: '福尔摩斯',
        level: 23,
        solved: 76,
        successRate: 96.2,
        avatar: '🎩'
      },
      {
        rank: 3,
        name: '波洛',
        level: 22,
        solved: 68,
        successRate: 94.8,
        avatar: '🧠'
      },
      {
        rank: 4,
        name: '马普尔小姐',
        level: 20,
        solved: 54,
        successRate: 92.3,
        avatar: '👵'
      },
      {
        rank: 5,
        name: '你',
        level: this.playerData?.level || 1,
        solved: this.playerData?.solvedCases || 0,
        successRate: this.playerData?.successRate || 0,
        avatar: '👤',
        isPlayer: true
      }
    ]
  },

  switchView(view) {
    this.currentView = view
  },

  changeTimeRange(range) {
    this.timeRange = range
    this.filterDataByTimeRange()
  },

  filterDataByTimeRange() {
    // 根据时间范围过滤数据
    // 这里可以实现具体的时间过滤逻辑
  },

  toggleComparisonMode() {
    this.comparisonMode = !this.comparisonMode
  },

  exportStatistics() {
    // 导出统计数据
    const exportData = {
      playerData: this.playerData,
      caseStatistics: this.caseStatistics,
      interrogationStats: this.interrogationStats,
      achievements: this.achievements,
      exportTime: new Date().toISOString()
    }
    
    storage.set({
      key: 'statisticsExport_' + Date.now(),
      value: JSON.stringify(exportData)
    })
    
    prompt.showToast({
      message: '统计数据已导出',
      duration: 2000
    })
  },

  shareAchievement(achievement) {
    // 分享成就
    const shareText = `我在侦探大师中解锁了成就：${achievement.name}！${achievement.description}`
    
    // 调用系统分享功能
    if (typeof system !== 'undefined' && system.share) {
      system.share({
        text: shareText,
        success: () => {
          prompt.showToast({
            message: '成就分享成功',
            duration: 2000
          })
        },
        fail: (error) => {
          prompt.showToast({
            message: '分享失败: ' + error.message,
            duration: 2000
          })
        }
      })
    }
  },

  viewDetailedStats(category) {
    // 查看详细统计
    router.push({
      uri: 'pages/detailedStats/detailedStats',
      params: {
        category: category,
        data: this.getCategoryData(category)
      }
    })
  },

  getCategoryData(category) {
    switch (category) {
      case 'cases':
        return this.caseStatistics
      case 'interrogation':
        return this.interrogationStats
      case 'skills':
        return this.playerData?.interrogationSkills || {}
      default:
        return {}
    }
  },

  refreshData() {
    // 刷新数据
    this.loadStatistics()
    this.generateChartData()
    this.calculateRankings()
    
    prompt.showToast({
      message: '数据已刷新',
      duration: 2000
    })
  },

  getProgressPercentage(current, target) {
    return Math.min(100, Math.round((current / target) * 100))
  },

  getSuccessRateColor(rate) {
    if (rate >= 90) return '#4caf50'
    if (rate >= 70) return '#ff9800'
    return '#f44336'
  },

  getDifficultyColor(difficulty) {
    switch (difficulty) {
      case 'easy': return '#4caf50'
      case 'medium': return '#ff9800'
      case 'hard': return '#f44336'
      default: return '#666666'
    }
  }
}